import { Box, Typography } from '@mui/material';
import MainLayout from 'components/HOCs/main-layout';
import { useEffect, useState } from 'react';

import DisbursementTable from '../../components/shared/tables/disbursement-table';
import { useLoadDisbursements } from '../../hooks/disbursement-load-more';
import { useInfiniteScroll } from '../../hooks/infinitive-scroll';

const DisbursementsPage = () => {
    const [pageLoading, setPageLoading] = useState(true);

    const { loading, items, hasNextPage, error, loadMore } = useLoadDisbursements();

    const [sentryRef] = useInfiniteScroll({
        loading,
        hasNextPage,
        onLoadMore: loadMore,
        disabled: !!error,
        rootMargin: '0px 0px 400px 0px'
    });

    useEffect(() => {
        const load = async () => {
            await loadMore();
            setPageLoading(false);
        };

        load().then();
    }, []);

    return (
        <MainLayout>
            <Box sx={{ p: 6 }}>
                <Typography variant="h2" color="white" sx={{ pb: 3 }}>
                    Disbursements
                </Typography>

                <DisbursementTable
                    pageLoading={pageLoading}
                    items={items}
                    error={error}
                    loading={loading}
                    hasNextPage={hasNextPage}
                    sentryRef={sentryRef}
                />
            </Box>
        </MainLayout>
    );
};

export default DisbursementsPage;
